package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class RedisSimpleLock implements RedisLock{

    private StringRedisTemplate stringRedisTemplate;
    private Long expire;
    private TimeUnit timeUnit;
    private String key;

    public RedisSimpleLock(StringRedisTemplate stringRedisTemplate, Long expire, TimeUnit timeUnit, String key) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.expire = expire;
        this.timeUnit = timeUnit;
        this.key = key;
    }

    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static DefaultRedisScript<Long> redisScript;
    static {
        redisScript = new DefaultRedisScript<>();
        redisScript.setLocation(new ClassPathResource("unlock.lua"));
        redisScript.setResultType(Long.class);
    }

    /**
     * 尝试获取锁
     */
    @Override
    public boolean tryLock() {
        Long threadId = Thread.currentThread().getId();
        String value = ID_PREFIX + threadId;
        // setnx设置值
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key, value, expire, timeUnit);
        return BooleanUtil.isTrue(success);
    }

    /**
     * 解锁
     */
    public void unLock() {
        // lua脚本实现判断锁归属与释放锁的原子性
        stringRedisTemplate.execute(redisScript,
                Collections.singletonList(key),
                ID_PREFIX + Thread.currentThread().getId());
    }

    /**
     * 解锁
     */
/*    @Override
    public void unLock() {
        // 判断当前锁是否属于自己
        Long threadId = Thread.currentThread().getId();
        String value = ID_PREFIX + threadId;
        String currentValue = stringRedisTemplate.opsForValue().get(key);
        if (value.equals(currentValue)) {
            // 删除key
            stringRedisTemplate.delete(key);
        }
    }*/
}
